/*
 * gulp-inject-string
 * https://github.com/Schmicko/gulp-inject-string
 *
 * Copyright (c) 2014 Michael Hazell
 * Licensed under the MIT license.
 */
var es = require('event-stream');

var stream = function (injectMethod) {
    return es.map(function (file, cb) {
        try {
            file.contents = Buffer.from(injectMethod(String(file.contents)));
        } catch (err) {
            return cb(new Error('gulpTypeGlobal', err));
        }
        cb(null, file);
    });
};

let rMap = {}

module.exports = {
    replace: function () {
        return stream(function (fileContents) {

            if (fileContents.indexOf("notype") != -1) return ""

            let search = /(export default class )(.+?) {/
            const str = fileContents.match(search);
            let endStr = ''

            if (str) {

                /**
                 * 是否是需要覆盖原生的类
                 * */
                const proClass = fileContents.indexOf("protype") != -1

                // console.log(str);
                let varName = str[0].match(search)[2]

                let tname = ''

                //判断是否有泛型
                const tindex = varName.indexOf('<')
                if (tindex != -1) {
                    tname = varName.substring(tindex)
                    varName = varName.substring(0, tindex)
                    // console.log(varName);
                    // console.log(tname);
                }

                if (proClass) {} else {
                    endStr = `declare var ${varName}: ${varName}Inter;\n`
                }
                rMap[varName] = varName + 'Inter'

                if (proClass) {
                    fileContents = fileContents.replace(search, `interface ${varName.substring(2)}${tname} {`)
                } else {
                    fileContents = fileContents.replace(search, `interface ${varName}Inter${tname} {`)
                }

                if (fileContents.indexOf("static ") != -1 || proClass) {
                    fileContents = fileContents.replace(/static /g, '')
                } else {
                    let newstr = /constructor\(([\s\S]+?)\);/
                    const newstrm = fileContents.match(newstr);
                    let newparam = ''
                    let indexof = fileContents.indexOf('constructor(param')
                    if (indexof != -1) {
                        // console.log(fileContents.substring(indexof,indexof+245));
                        // console.log(newstrm);
                    }
                    if (newstrm) {
                        newparam = newstrm[1]
                    }
                    // let startIndex = fileContents.indexOf('{')
                    // let endIndex = fileContents.length - 2
                    // const ctx = "\nnew" + newparam + ": {" + fileContents.substring(startIndex + 1, endIndex) + "}\n"
                    // fileContents = fileContents.substring(0, startIndex) + "{" + ctx + "}\n"

                    endStr = `interface ${varName}Obj { new ${tname}(${newparam}):${varName}Inter${tname.replace(/=(.+?)>/g,'>').replace(/=(.+?),/g,',').replace(/\s/g,'')}}\n` + `declare var ${varName}: ${varName}Obj;\n`
                }
            }
            return fileContents + endStr;
        });
    },

    replaceName: function () {
        return stream(function (fileContents) {
            if (fileContents.length < 10) return fileContents
            // console.log(rMap);
            const keys = Object.keys(rMap)
            const replaceExtends = (strre, strres) => {
                const re = new RegExp(strre, 'g')
                const arr = Array.from(re[Symbol.matchAll](fileContents)).map(item => item[0])
                if (arr.length > 0) {
                    fileContents = fileContents.replaceAll(re, strres)
                }
            }
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i]
                replaceExtends(`extends ${key} `, `extends ${rMap[key]} `)
                replaceExtends(`: ${key};`, `: ${rMap[key]};`)
                replaceExtends(`: ${key}\\[`, `: ${rMap[key]}\[`)
                replaceExtends(`: ${key},`, `: ${rMap[key]},`)
                replaceExtends(`: ${key}\\(`, `: ${rMap[key]}\(`)
                replaceExtends(`: ${key}\\)`, `: ${rMap[key]}\)`)
                // if (str) {
                //     console.log(str,key);
                //     fileContents = fileContents.replace(re, '$1extends$2'+rMap[key]+' {')
                // }
            }
            return fileContents;
        });
    }
};

module.exports._stream = stream;